package com.wpre.vampiremq.common;

import java.io.*;

/**
 * Created with IntelliJ IDEA.
 * Description: 序列化和反序列化的工具
 * User: LianBao
 * Date: 2025-01-14
 * Time: 14:25
 */
public class BinaryTool {
    /**
     * 把对象序列化成字节数组
     * @return
     */
    public static byte[] toBytes(Object object) throws IOException {
        //相当于一个变长的字节数组,因为不知道传过来的数据长度不确定
        //可以把Object中的数据写入到ByteArrayOutputStream中,最后再转换成byte[]
        //ByteArrayOutputStream可以不关闭
        try (ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream()) {
            try (ObjectOutputStream outputStream = new ObjectOutputStream(byteArrayOutputStream)) {
                //进行序列化操作
                //writeObject会把对象进行序列化,生成的二进制字节数据会写入到ObjectOutputStream中,而ObjectOutputStream又关联到了byteArrayOutputStream
                //所以实际上是写入到了byteArrayOutputStream这个字节数组中
                outputStream.writeObject(object);
            }
            //再将byteArrayOutputStream转换成byte[]
            return byteArrayOutputStream.toByteArray();
        }
    }

    /**
     * 把字节数组反序列化成对象
     * @param data
     * @return
     */
    public static Object fromBytes(byte[] data) throws IOException, ClassNotFoundException {
        Object o = null;
        try (ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(data)) {
            try (ObjectInputStream inputStream = new ObjectInputStream(byteArrayInputStream)){
                //进行反序列化操作
                o = inputStream.readObject();
            }
        }
        return o;
    }

}
